# 在文件顶部添加Django环境初始化
import json
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'buyHigh.settings.settings_dev')
django.setup()
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from user.models import UserProfile
from django.contrib.auth.models import AnonymousUser
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class BalanceConsumer(AsyncWebsocketConsumer):
    """WebSocket消费者，用于实时推送用户余额变更"""
    async def connect(self):
        """处理WebSocket连接请求"""
        #   从url路径参数中获取用户ID
        user = self.scope['user']
        # 验证用户是否登录
        print('ws中获取到的user',user)
        if not user.is_authenticated:
            print('未登录')
            await self.close(code=4001)  # 自定义关闭代码
            return
        print('已登录')
        self.user_id = user.id  # 使用认证用户的ID
        #创建用户专属频道组名
        self.group_name = f'balance_{self.user_id}'
        # 将当前用户加入到频道组中
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        print('成功建立连接')
        # 接受WebSocket连接
        await self.accept()

    async def disconnect(self, close_code):
        """处理WebSocket断开连接请求"""
        # 确保 group_name 已初始化
        if hasattr(self, 'group_name'):
            print('断开链接')
            # 从频道组中移除当前连接
            await self.channel_layer.group_discard(
                self.group_name,
                self.channel_name
            )

    async def balance_update(self, event):
        """
            处理余额变更事件
            event:来自频道层的消息事件
        """
        # 从数据库异步获取最新余额
        new_balance = await self.get_balance()
        print('new_balance', new_balance)
        # 向客户端发送最新余额（转换为字符串格式
        await self.send(text_data=str(new_balance))

    @database_sync_to_async
    def get_balance(self):
        """
        同步数据库操作包装为异步方法
        获取当前用户的余额信息
        """
        user = UserProfile.objects.get(id=self.user_id)  #根据用户ID获取用户对象
        return user.balance # 返回最新余额值


# ... existing code ...

class CustomerServiceConsumer(AsyncWebsocketConsumer):
    """处理客户与客服的实时对话"""
    async def connect(self):
        user = self.scope['user']
        if not user.is_authenticated:
            await self.close(code=4001)
            return
        # 客户加入客服队列频道
        self.group_name = 'customer_service'
        # self.group_name应该是用户定义的群组名称，比如在之前的代码中，
        # 用户可能为每个用户创建了特定的群组，比如'balance_{user_id}'。
        # 而self.channel_name是当前WebSocket连接的唯一频道名称，由Channels自动生成。
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        await self.accept()

    async def receive(self, text_data):
        """接收客户端的消息"""
        # 广播消息给所有客服
        await self.channel_layer.group_send(
            "support_staff",  # 客服群组
            {
                "type": "customer_message",
                "message": text_data,
                "user_id": str(self.scope['user'].id)
            }
        )


class SupportStaffConsumer(AsyncWebsocketConsumer):
    """客服人员使用的Consumer"""
    async def connect(self):
        user = self.scope['user']
        if not user.is_authenticated or not user.is_staff:
            await self.close(code=4001)
            return

        # 加入客服专用频道
        await self.channel_layer.group_add(
            "support_staff",
            self.channel_name
        )
        await self.accept()

    async def customer_message(self, event):
        """接收客户消息并转发给客服"""
        await self.send(text_data=json.dumps({
            "type": "new_message",
            "message": event["message"],
            "user_id": event["user_id"]
        }))
